package com.yao_shop.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.yao_shop.service.Impl.token_serviceImpl;
import com.yao_shop.service.Impl.yao_serviceImpl;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
public class yaoController {
    @Autowired
    yao_serviceImpl yao_ser;
    @Autowired
    token_serviceImpl token_service;

    @ApiOperation(value = "登录",notes = "登通过用户名密码登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "stu_phone", value = "手机号/账号", required = true, example = "15090401097"),
            @ApiImplicitParam(name = "stu_password", value = "密码", required = true, example = "00000")
    })
    @PostMapping(value="/login.do")
    public String yao_login(@RequestParam Map map, HttpServletRequest request) throws Exception {
        String header = request.getHeader("token");
        boolean token1 = token_service.panduan(header);
        if (token1==true) {
            return "此用户已经登录，请先返回首页注销！";
        } else {
            Map login_info = yao_ser.yao_login(map);
            //通过session存储 用户名
            if (login_info.size() != 0) {
                String userAgent = request.getHeader("user-agent");
                String stu_phone = map.get("stu_phone").toString();
                String token = this.token_service.generateToken(userAgent, stu_phone);
                this.token_service.save(token, login_info);
                System.out.println(login_info + "登陆成功！");
                Object stu_name = login_info.get("stu_name");
//            request.getSession().setAttribute("session_name",stu_name);
                System.out.println(JSONObject.toJSONString(token));
                return token.toString();
            } else {
                System.out.println("账号或密码错误");
                return "fail";
            }

        }
    }

//    @ApiOperation(value = "session名字",notes = "登录之后的用户名")
//    @GetMapping(value="/session_name.do")
//    public String session_name(Map map,HttpServletRequest request){
//        try{
//            Object session_name = request.getSession().getAttribute("session_name");
//            System.out.println("sessionname"+session_name);
//            if (session_name == null){
//                return "未登陆账号，请先登录。。。。";
//            }else{
//                return session_name.toString();
//            }
//        }catch (NullPointerException e){
//            return "未登录";
//        }
//}


}
